// 引入policy编码计算方法
import {
	getPolicyEncode
} from './hwObs/getPolicy.js'
// 引入签名计算方法
import {
	getSignature
} from './hwObs/getSignature.js'

import env from '@/pagesA/config/env';


function uuid() {
	var s = [];
	var hexDigits = '0123456789abcdef';
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 16), 1);
	}
	s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 3) | 8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = '-';
	var uuid = s.join('');
	return uuid;
}
export const OBSupload = function(filePath, callback) {
	const cisdiHwConfig = uni.getStorageSync('cisdiHwConfig');
	var configuration = {};
	if (cisdiHwConfig) {
		configuration = {
			AccessKeyId: cisdiHwConfig.ak,
			//AK
			SecretKey: cisdiHwConfig.sk,
			//SK
			Bucket: cisdiHwConfig.bucket,
			//Bucket
			EndPoint: `${env.uploadImgUrl}/${cisdiHwConfig.bucket}` //完整的桶访问域名
		};
	}
	if (!filePath) {
		console.log('filePath为空');
	} else {
		let key = `${uuid()}.${filePath.split('.')[filePath.split('.').length - 1]}`;
		let nextDay = new Date(new Date().getTime() + 86400 * 1000).toISOString();
		const OBSPolicy = {
			expiration: nextDay,
			conditions: [{
					bucket: configuration.Bucket
				},
				{
					key: key
				}
			]
		};
		const policyEncoded = getPolicyEncode(OBSPolicy);
		const signature = getSignature(policyEncoded, configuration.SecretKey);
		uni.uploadFile({
			filePath: filePath,
			name: 'file',
			url: configuration.EndPoint,
			header: {
				'content-type': 'multipart/form-data;'
			},
			formData: {
				AccessKeyID: configuration.AccessKeyId,
				policy: policyEncoded,
				signature,
				key
			},
			success: (res) => {
				if (res.statusCode == '204' && callback) {
					callback({
						code: 0,
						url: `https://${cisdiHwConfig.bucket}.${cisdiHwConfig.endpoint}/${key}`
					});
				} else {
					uni.showToast({
						title: '上传文件失败',
						icon: 'error'
					});
					callback({
						code: -1,
						url: ''
					});
				}
			},
			fail: (e) => {
				console.log(e);
				callback({
					code: -1,
					url: ''
				});
				uni.showToast({
					title: '上传文件失败',
					mask: true
				});
			}
		});
	}
};